package com.nisure.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.nisure.AutoKeywordApplication;
import com.nisure.info.KeywordTypeInfo;
import com.nisure.service.AccountService;
import com.nisure.service.AdgroupService;
import com.nisure.service.CampaignService;
import com.nisure.service.KeywordService;

@Component
public class ScheduleController {

	private static final Logger logger = LoggerFactory.getLogger(AutoKeywordApplication.class);
	@Autowired 
	private AccountController accountController;
	@Autowired
	private CampaignController campaignController;
	@Autowired
	private AdgroupController adgroupController;
	@Autowired
	private KeywordController keywordController;
	@Autowired
	private AccountService accountService;
	@Autowired
	private AdgroupService adgroupService;
	@Autowired
	private KeywordService keywordService;
	@Autowired
	private CampaignService campaignService;
	
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Scheduled(cron="0 0 0 * * ?")
	public void Scheduled(){
		Date start = new Date();
		logger.info("开始定时任务:"+sdf.format(start));
		List<Long> userIdList = accountService.queryAllUserId();
		campaignService.deleteAllCampaign(userIdList);
		adgroupService.deleteAllAdgroup(userIdList);
		keywordService.deleteAllKeyword(userIdList);
		
		for(long userId : userIdList){
		logger.info("用户:"+userId);
		String refreshToken = accountController.getRefreshToken(userId);
		JSONObject jsonObject = accountController
				.getAccessTokenByRF(refreshToken);
		
		String accessToken = jsonObject.getString("access_token");
		String newRefreshToken = jsonObject.getString("refresh_token");
		if(newRefreshToken==null){
			logger.info(userId+"获取rf失败");
			continue;
		}
		accountController.updateRefreshToken(userId, newRefreshToken);
		
		List<Long> campaignIdList = campaignController.saveAllCampaign(accessToken,userId);
		if(campaignIdList==null||campaignIdList.isEmpty()){
			logger.info(userId+"获取计划数据失败");
			continue;
		}
		
		List<Long> adgroupIdList = adgroupController.saveAllAdgroup(accessToken, campaignIdList,userId);
		if(adgroupIdList==null){
			logger.info(userId+"获取单元数据失败");
			continue;
		}
		
		List<KeywordTypeInfo> KeywordList = keywordController.saveAllKeyword(accessToken, adgroupIdList,userId);
		if(KeywordList==null){
				logger.info(userId+"获取关键词数据失败");
				continue;
		}				
		}
		Date end = new Date();
		logger.info("结束定时任务:"+sdf.format(end));
		
	}
}
